<template>
    <div class="subject-content">
        <el-form :model="queryParams" size="medium" ref="queryForm" label-width="75px">

            <el-form-item label="角色名称" prop="roleName" size="mini">
                <el-input v-model="queryParams.roleName" clearable placeholder="请输入角色名称"></el-input>
            </el-form-item>

            <el-form-item label="权限字符" prop="roleKey" size="mini">
                <el-input v-model="queryParams.roleKey" clearable placeholder="请输入权限字符"></el-input>
            </el-form-item>

            <el-form-item label="状态" prop="roleStatus" size="mini">
                <el-select v-model="queryParams.roleStatus" placeholder="请选择角色状态" clearable>
                    <el-option v-for="(item, index) in dict.dictType.role_status" :key="index" :label="item.dictLabel"
                               :value="item.dictValue"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item size="mini">
                <el-button type="primary" icon="el-icon-search" @click="searchQuery">提交</el-button>
                <el-button type="primary" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>

        </el-form>

        <el-row :gutter="10" style="margin-bottom: 15px">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleUpdate">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" @click="handleDelete" size="mini">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading"
                           @click="exportExcel">导出
                </el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
            <el-table-column fixed="left" type="selection" width="55" align="center"/>
            <el-table-column label="角色编号" prop="roleId" width="120" sortable align="center"/>
            <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" width="150"/>
            <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" width="150"/>
            <el-table-column label="状态" align="center" width="100">
                <template v-slot="scope">
                    <el-switch v-model="scope.row.roleStatus" active-value="0" inactive-value="1"
                               @change="handleStatusChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" sortable width="200">
                <template v-slot="scope">
                    <span>{{ scope.row.createTime }}</span>
                </template>
            </el-table-column>

            <el-table-column label="更新时间" align="center" prop="createTime" sortable width="200">
                <template v-slot="scope">
                    <span>{{ scope.row.updateTime }}</span>
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
                <template v-slot="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="rowUpdate(scope.row)">修改
                    </el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="rowDelete(scope.row)">删除
                    </el-button>
                    <el-dropdown v-if="scope.row.roleKey != 'admin'" size="mini" @command="(command) => handleCommand(command, scope.row)">
                        <span class="el-dropdown-link"><i class="el-icon-d-arrow-right el-icon--right"></i>更多</span>
                        <el-dropdown-menu v-slot="dropdown">
                            <el-dropdown-item command="dataPermissions" icon="el-icon-circle-check">数据权限
                            </el-dropdown-item>
                            <el-dropdown-item command="allocationUser" icon="el-icon-user">分配用户</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>

        </el-table>

        <page
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.current"
                :limit.sync="queryParams.size"
                @pagination="getList"
        />

        <!-- 添加或修改角色配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>

            <el-form ref="roleForm" :model="roleForm" :rules="rules" size="small" label-width="100px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="角色名称" prop="roleName">
                            <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" clearable></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="权限字符" prop="roleKey">
                            <el-input v-model="roleForm.roleKey" placeholder="请输入权限字符" clearable></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="账号状态" prop="roleStatus">
                            <el-radio-group v-model="roleForm.roleStatus" size="medium">
                                <el-radio v-for="(item, index) in dict.dictType.role_status" :key="index"
                                          :label="item.dictValue">
                                    {{ item.dictLabel }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="菜单权限" style="width: 400px;">
                            <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选
                            </el-checkbox>
                            <el-tree
                                    class="tree-border"
                                    :data="menuOptions"
                                    show-checkbox
                                    ref="menu"
                                    node-key="id"
                                    :check-strictly="false"
                                    empty-text="加载中，请稍候"
                                    :props="defaultProps"
                            ></el-tree>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {
    selectRoleByid,
    roleList,
    updateRole,
    updateRoleStatus,
    addRole,
    roleExportExcel,
    deleteRoleById,
    deleteRoleByIds
} from "@/api/admin/role/role";
import {roleMenuTreeselect, menuTreeselect} from "@/api/admin/menu";
import Page from "@/components/page.vue";

export default {
    name: "role",
    dicts: ["role_status"],
    components: {Page},
    data() {
        return {
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 是否显示弹出层
            open: false,
            // 弹出层标题
            title: "",
            // 选中数组
            ids: [],
            // 总条数
            total: 0,

            // 查询参数  current 当前页   size 页大小
            queryParams: {
                current: 1,
                size: 10,
                roleName: undefined,
                roleKey: undefined,
                roleStatus: undefined
            },

            //表格数据
            roleList: [],
            // 表单参数
            roleForm: {},
            // 表单数据校验
            rules: {
                roleName: [{
                    required: true,
                    message: '请输入角色名称',
                    trigger: 'blur'
                }],
                roleKey: [{
                    required: true,
                    message: '请输入权限字符',
                    trigger: 'blur'
                }]
            },
            // 菜单树状列表
            menuOptions: [],
            // 树形props参数
            defaultProps: {
                children: "children",
                label: "label"
            },
            menuNodeAll: false,
        }
    },
    methods: {
        /** 查询所有角色*/
        getList() {
            roleList(this.queryParams).then(res => {
                this.roleList = res.data.records;
                this.total = res.data.total;
                this.loading = false;
            })
        },
        /** 搜索按钮操作 */
        searchQuery() {
            this.queryParams.current = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.searchQuery();
        },
        /** 表单重置 */
        reset() {
            this.roleForm = {
                roleId: undefined,
                roleName: undefined,
                roleKey: undefined,
                roleStatus: undefined,
                menuIds: [],
            };
            this.resetForm("roleForm");
        },

        /** 获取当前角色所拥有的 菜单*/
        getMenuTreeselect() {
            menuTreeselect().then(res => {
                this.menuOptions = res.data;
            });
        },

        /** 头工具栏--添加*/
        handleAdd() {
            this.reset();
            this.getMenuTreeselect();
            this.roleForm.roleStatus = "0"
            this.open = true;
            this.title = "添加角色";
        },
        /** 头工具栏--修改*/
        handleUpdate() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning('请选择要修改的角色！');
            } else if (this.ids.length > 1) {
                this.$modal.msgWarning('请选择一个角色进行修改！');
            } else {
                this.reset();
                const roleId = this.ids;
                //根据角色ID获取菜单下拉树列表 (1、 获取当前登录的角色菜单 2、在获取当前修改角色的导航菜单id 3、同过id判断 在当前登录的校色下 修改的角色有哪些写导航权限)
                const roleMenu = this.getRoleMenuTreeselect(roleId);
                selectRoleByid(roleId).then(res => {
                    this.roleForm = res.role_data;
                    this.title = "修改角色";
                    this.$nextTick(() => {
                        roleMenu.then(res => {
                            let role_id_list = res.menu_id
                            role_id_list.forEach((v) => {
                                this.$nextTick(() => {
                                    this.$refs.menu.setChecked(v, true, false);
                                })
                            })
                        });
                    });
                    this.open = true;
                })
            }
        },
        /** 头工具栏--删除*/
        handleDelete() {
            if (this.ids.length === 0) {
                this.$modal.msgWarning('请选择要删除的角色！')
            } else {
                const roleIds = this.ids;
                const size = roleIds.length;
                this.$modal.confirm('是否确认删除？').then(function () {
                    return deleteRoleByIds(roleIds);
                }).then(res => {
                    this.getList();
                    this.$modal.msgSuccess(res.msg + "," + size + "条数据");
                });
            }
        },
        /**头工具栏--导出*/
        exportExcel() {
            this.$modal.confirm('是否导出当前搜索结果？').then(() => {
                this.exportLoading = true;
                return roleExportExcel(this.queryParams)
            }).then(res => {
                this.$download.name(res.data);
                this.exportLoading = false;
            });
        },
        /**取消按钮 */
        cancel() {
            this.open = false;
            this.reset();
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs.roleForm.validate(valid => {
                if (valid) {
                    if (this.roleForm.roleId != undefined) {
                        this.roleForm.menuIds = this.getMenuAllCheckedKeys();
                        updateRole(this.roleForm).then(() => {
                            this.$modal.msgSuccess("修改成功")
                            this.open = false;
                            this.getList();
                        })
                    } else {
                        this.roleForm.menuIds = this.getMenuAllCheckedKeys();
                        addRole(this.roleForm).then(() => {
                            this.$modal.msgSuccess("添加成功")
                            this.open = false;
                            this.getList();
                        })
                    }
                }
            });
        },
        //行工具栏--删除
        rowDelete(row) {
            const roleId = row.roleId
            this.$modal.confirm('是否确认删除？').then(function () {
                return deleteRoleById(roleId)
            }).then(res => {
                this.getList();
                this.$modal.msgSuccess(res.msg);
            });
        },
        //行工具栏--修改
        rowUpdate(row) {
            this.reset();
            const roleId = row.roleId;
            //根据角色ID获取菜单下拉树列表 (1、 获取当前登录的角色菜单 2、在获取当前修改角色的导航菜单id 3、同过id判断 在当前登录的校色下 修改的角色有哪些写导航权限)
            const roleMenu = this.getRoleMenuTreeselect(roleId);
            selectRoleByid(roleId).then(res => {
                this.roleForm = res.role_data;
                this.title = "修改角色";
                this.$nextTick(() => {
                    roleMenu.then(res => {
                        let role_id_list = res.menu_id
                        role_id_list.forEach((v) => {
                            this.$nextTick(() => {
                                this.$refs.menu.setChecked(v, true, false);
                            })
                        })
                    });
                });
                this.open = true;
            })
        },

        // 工具行--更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case "dataPermissions":
                    this.dataPermissions(row);
                    break;
                case "allocationUser":
                    this.allocationUser(row);
                    break;
                default:
                    break;
            }
        },

        // 分配用户
        allocationUser: function (row) {
            const roleId = row.roleId;
            this.$router.push("/system/role-user/" + roleId);
        },

        // 数据权限
        dataPermissions: function (row) {
            const roleId = row.roleId;
            this.$router.push("/system/role-data/" + roleId);
        },

        //角色状态修改
        handleStatusChange(row) {
            let text = row.roleStatus === "0" ? "启用" : "停用";
            this.$modal.confirm("确认要" + text + row.roleName + "角色吗？").then(function () {
                return updateRoleStatus(row.roleId, row.roleStatus);
            }).then(res => {
                this.$modal.msgSuccess(text + res.msg);
            }).catch(function () {
                row.roleStatus = row.roleStatus === "0" ? "1" : "0";
            });
        },

        //多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.roleId)
        },
        //所有菜单节点数据
        getMenuAllCheckedKeys() {
            // 目前被选中的菜单节点
            let checkedKeys = this.$refs.menu.getCheckedKeys();
            // 半选中的菜单节点
            let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
            checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
            return checkedKeys;
        },
        //根据角色ID获取菜单下拉树列表 (1、 获取当前登录的角色菜单 2、在获取当前修改角色的导航菜单id 3、同过id判断 在当前登录的校色下 修改的角色有哪些写导航权限)
        getRoleMenuTreeselect(roleId) {
            return roleMenuTreeselect(roleId).then(res => {
                this.menuOptions = res.role_menu_data;
                return res;
            });
        },
        // 树权限（全选/全不选）
        handleCheckedTreeNodeAll(value) {
            this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
        },
    },
    created() { // 初始化
        this.getList();
    }
}
</script>

<style scoped>

.el-row {
    display: inline-block;
}
.el-form-item {
    display: inline-block;
}

/deep/ .el-dialog {
    position: fixed !important;
    right: 0 !important;
    top: 0 !important;
    z-index: 2500 !important;
    margin-top: 0 !important;
    height: 100%;
}

</style>
